import { Toast } from 'antd-mobile'
import { reqLogin } from '../../request/api'
//初始状态
const initState = {
    //1.初始化表单数据
    user: {
        phone: '',
        password: ''
    },
    userInfo:sessionStorage.getItem('userinfo')?JSON.parse(sessionStorage.getItem('userinfo')):{}
}

// actionType
const TYPES = {
    // 2.修改user的type
    LOGIN_CHENGE_USER: 'LOGIN_CHENGE_USER',
    LOGIN_CHANGE_USERINFO: 'LOGIN_CHANGE_USERINFO'
}

// reducer
const reducer = (state = initState, action) => {
    switch (action.type) {
        // 3.具体修改user
        case TYPES.LOGIN_CHENGE_USER:
            return {
                ...state,
                user: {
                    ...state.user,
                    [action.key]: action.value
                }
            }
        // 修改userinfo
        case TYPES.LOGIN_CHENGE_USER:
            return {
                ...state,
                userInfo: action.userInfo
            }
        default:
            return state;
    }
}

// actionCreators
export const actions = {
    // 4.修改userinfo的action
    changeUser: (key, value) => ({ type: TYPES.LOGIN_CHENGE_USER, key, value }),
    // 修改用户信息
    changeUserInfo: (userInfo) => {
        // 同步到本地存储
        if (userInfo.token) {//存储
            sessionStorage.setItem('userinfo', JSON.stringify(userInfo))
        } else {//删除
            sessionStorage.removeItem('userinfo')
        }
        return { type: TYPES.LOGIN_CHANGE_USERINFO, userInfo }
    },
    // 点击登录按钮
    doLogin: (push) => {
        return (dispatch, getState) => {
            reqLogin(getUser(getState())).then(res => {
                if (res.data.code == 200) {
                    // 成功
                    Toast.show({
                        content: res.data.msg
                    })
                    // 存储用户信息到仓库
                    dispatch(actions.changeUserInfo(res.data.list))
                    // 跳转页面
                    push('/index/home')
                }
            })
        }
    }
}

// selectors
// 5.导出数据user
export const getUser = state => state.login.user;
export const getUserInfo = state => state.login.userInfo;
// 导出reducer
export default reducer